// 三数之和
var threeSum = function (nums) {
  let result = []
  if (nums === null || nums.length < 3) return result
  nums.sort((a, b) => a - b)

  for (let first = 0; first < nums.length - 2; first++) {
    if (nums[first] > 0) break
    if (first > 0 && nums[first] === nums[first - 1]) continue
    let second = first + 1
    let third = nums.length - 1
    while (second < third) {
      const sum = nums[first] + nums[second] + nums[third]
      if (sum === 0) {
        result.push([nums[first], nums[second], nums[third]])
        while (second < third && nums[second] === nums[second + 1]) second++
        while (second < third && nums[third] === nums[third - 1]) third--
        second++
        third--
      } else if (sum > 0) {
        third--
      } else if (sum < 0) {
        second++
      }
    }
  }
  return result
}

var threeSum = function (nums) {
  let result = []
  if (nums === null || nums.length < 3) return result
  nums.sort((a, b) => a - b)
  for (let first = 0; first < nums.length - 2; first++) {
    if (nums[first] > 0) break
    if (first > 0 && nums[first] === nums[first - 1]) continue
    let third = nums.length - 1
    for (let second = first + 1; second < nums.length - 1; second++) {
      if (second > first + 1 && nums[second] === nums[second - 1]) continue
      while (second < third && nums[first] + nums[second] + nums[third] > 0)
        third--
      if (second === third) break
      if (nums[first] + nums[second] + nums[third] === 0) {
        result.push([nums[first], nums[second], nums[third]])
      }
    }
  }
  return result
}
